package cuckoo.ioc.container;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import cuckoo.ioc.container.config.ScannerListner;
import cuckoo.ioc.scanner.BeanScanner;

public abstract class ScanBeanContainer extends BeanFactoryContainer {

	private String packageName;

	private BeanScanner scanner = new BeanScanner();

	private List<ScannerListner> listners = new ArrayList<ScannerListner>();

	public ScanBeanContainer(String packageName) {
		this.packageName = packageName;
	}

	protected void doScan() throws IOException {
		Set<Class<?>> classes = scanner.doScan(packageName.replace('.', '/'));
		filterClass(classes);
		register(classes.toArray(new Class<?>[classes.size()]));
	}

	private void filterClass(Set<Class<?>> classes) {
		List<Class<?>> removes = new ArrayList<Class<?>>();

		for (Class<?> clazz : classes) {
			for (ScannerListner listner : listners) {
				if (listner.filterClass(clazz)) {
					removes.add(clazz);
					break;
				}
			}
		}

		classes.removeAll(removes);
	}

	public void addScannerListner(ScannerListner listner) {
		listners.add(listner);
	}

}